﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Model;

namespace TaxiDispatchClient
{
    public partial class AdMachineAddFromExcelForm : DevExpress.XtraEditors.XtraForm
    {
        public AdMachineAddFromExcelForm()
        {
            InitializeComponent();
        }

        private DataTable _dt;

        private void btn_openExcel_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "Excel文件|*.xls";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string filepath = openFileDialog1.FileName;
             
                DataSet ds = Service.ExcelCommon.LoadDataFromExcel(filepath);
                if (ds==null || ds.Tables.Count==0)
                {
                    XtraMessageBox.Show("请先关闭想要导入的Excel文件！");
                    return;
                }
                if (!CheckExcelColumns(ds.Tables[0]))
                {
                    return;
                }
                _dt = ds.Tables[0];                
                gridControl1.DataSource = ds.Tables[0];
                int count = ds.Tables[0].Rows.Count;
                gridView1.GroupPanelText = "共有数据" + count
                +"条   （注：若下方表中有未显示的数据，请核对您的Excel表格中各个标题是否与本表标题相同）";
                btn_beginAdd.Enabled = true;

                progress1.Visible = false;
                label_compelete.Visible = false;
                label_lose.Visible = false;
            }
            
        }

        private bool CheckExcelColumns(DataTable dt)
        {
            if (dt == null)
            {
                return false;
            }
            if (!dt.Columns.Contains("编号"))
            {
                XtraMessageBox.Show("选择的Excel文件中未找到【编号】列。" +
                                    Environment.NewLine
                    +"请确保选择的Excel表格中各个标题是否与本表标题相同！");
                return false;
            } 
            if (!dt.Columns.Contains("站点名称"))
            {
                XtraMessageBox.Show("选择的Excel文件中未找到【站点名称】列。" +
                                    Environment.NewLine
                    + "请确保选择的Excel表格中各个标题是否与本表标题相同！");
                return false;
            }
            if (!dt.Columns.Contains("经度"))
            {
                XtraMessageBox.Show("选择的Excel文件中未找到【经度】列。" +
                                    Environment.NewLine
                    + "请确保选择的Excel表格中各个标题是否与本表标题相同！");
                return false;
            }
            if (!dt.Columns.Contains("纬度"))
            {
                XtraMessageBox.Show("选择的Excel文件中未找到【纬度】列。" +
                                    Environment.NewLine
                    + "请确保选择的Excel表格中各个标题是否与本表标题相同！");
                return false;
            }
            if (!dt.Columns.Contains("联系人"))
            {
                XtraMessageBox.Show("选择的Excel文件中未找到【联系人】列。" +
                                    Environment.NewLine
                    + "请确保选择的Excel表格中各个标题是否与本表标题相同！");
                return false;
            }
            if (!dt.Columns.Contains("联系人手机号"))
            {
                XtraMessageBox.Show("选择的Excel文件中未找到【联系人手机号】列。" +
                                    Environment.NewLine
                    + "请确保选择的Excel表格中各个标题是否与本表标题相同！");
                return false;
            }
            if (!dt.Columns.Contains("详细地址"))
            {
                XtraMessageBox.Show("选择的Excel文件中未找到【详细地址】列。" +
                                    Environment.NewLine
                    + "请确保选择的Excel表格中各个标题是否与本表标题相同！");
                return false;
            }
            if (!dt.Columns.Contains("联网方式"))
            {
                XtraMessageBox.Show("选择的Excel文件中未找到【联网方式】列。" +
                                    Environment.NewLine
                    + "请确保选择的Excel表格中各个标题是否与本表标题相同！");
                return false;
            }
            if (!dt.Columns.Contains("XT800号码"))
            {
                XtraMessageBox.Show("选择的Excel文件中未找到【XT800号码】列。" +
                                    Environment.NewLine
                    + "请确保选择的Excel表格中各个标题是否与本表标题相同！");
                return false;
            }
            if (!dt.Columns.Contains("退出密码"))
            {
                XtraMessageBox.Show("选择的Excel文件中未找到【退出密码】列。" +
                                    Environment.NewLine
                    + "请确保选择的Excel表格中各个标题是否与本表标题相同！");
                return false;
            }
           
            return true;
        }

        private void btn_beginAdd_Click(object sender, EventArgs e)
        {
            if (_dt==null || _dt.Rows.Count==0)
            {
                XtraMessageBox.Show("请先选择Excel文件!");
                return;
            }
            btn_beginAdd.Enabled = false;
            Thread thread = new Thread(AddToDatabase);
            thread.IsBackground = true;
            thread.Start();
        }

        private void AddToDatabase()
        {             
            StringBuilder erroStr = new StringBuilder();
            int succeed =0;
            int lose = 0;
            int total = _dt.Rows.Count;


            BeginInvoke(new MethodInvoker(() =>
            {
                progress1.Visible = true;
                label_compelete.Visible = true;
                label_lose.Visible = true;
                progress1.Properties.Minimum = 0;
                progress1.Properties.Maximum = total;
            }));
          
            //label_compelete.Text = 0 + " / " + total;
            
            for (int i = 0; i < _dt.Rows.Count;i++ )
            {
                DataRow row = _dt.Rows[i];
                ADMachineInfo model = new ADMachineInfo();
                model.Number = row["编号"].ToString();
                model.StationName = row["站点名称"].ToString();
                if (string.IsNullOrEmpty(model.Number))
                {
                    erroStr.Append("第" + (i+1) + "行，编号为空；");
                    erroStr.Append("\r\n");
                    lose++;
                    continue;                
                }

                if (MainForm.PositionService.AdMachineExists(model.Number))
                {
                    erroStr.Append("第" + (i + 1) + "行，编号在数据库中已被占用；");
                    erroStr.Append("\r\n");
                    lose++;
                    continue;                
                }
                
                if (string.IsNullOrEmpty(model.StationName))
                {
                    erroStr.Append("第" + (i + 1) + "行，站点名称为空；");
                    erroStr.Append("\r\n");
                    lose++;
                    continue;
                } 

                 
                double dvalue;
                if (double.TryParse(row["经度"].ToString(), out dvalue))
                {
                    model.Longitude = dvalue;
                }
                else
                {
                    erroStr.Append("第" + (i + 1) + "行：精度格式不对");
                    erroStr.Append("\r\n");
                    lose++;
                    continue;                    
                }
                if (double.TryParse(row["纬度"].ToString(), out dvalue))
                {
                    model.Latitude = dvalue;
                }
                else
                {
                    erroStr.Append("第" + (i + 1) + "行：纬度格式不对");
                    erroStr.Append("\r\n");
                    lose++;
                    continue;
                }                
                model.Linkman = row["联系人"].ToString();
                model.PhoneNumber = row["联系人手机号"].ToString();
                model.Telephone = row["座机"].ToString();
                model.Address = row["详细地址"].ToString();
                model.InternetType = row["联网方式"].ToString();
                model.XTRemoteId = row["XT800号码"].ToString();
                int exitPwd = 0;
                int.TryParse(row["退出密码"].ToString(), out exitPwd);                 
                model.ExitPassword = exitPwd.ToString();
                 
                if (!MainForm.PositionService.AdMachineAdd(model))
                {

                    erroStr.Append("第" + (i + 1) + "行：添加数据库失败");
                    erroStr.Append("\r\n");
                    lose++;
                    continue;
                }
                else
                {
                    succeed++;                   
                }
                BeginInvoke(new MethodInvoker(() =>
                {
                    progress1.Position = succeed;
                    label_compelete.Text = "完成:" + succeed + "/" + total;
                    label_lose.Text = "失败:"+lose;
                }));
            }
            string result = "导入结果：\r\n共计" +
                total + "条，\r\n成功添加" + succeed + "条\r\n";
            if (erroStr.ToString()!="")
            {
                result += "失败" + lose + "条,失败原因如下：\r\n";
                result += erroStr.ToString();
            }
            XtraMessageBox.Show(result);
        }


        #region 窗体控件效果
        Point _mouseOff;
        bool _leftFlag;
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }

        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexitPressDown;

            Cursor = Cursors.Arrow;

        }
        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
        }

        private void pictureEdit_exit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void PhoneUserForm_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Close();
            }
        }
        #endregion
    }
}